package com.bainuo.doctor.common.util;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2018/2/7.
 * soundPool 管理类
 */
public class SoundPoolManager {

    private static Map<Integer, Integer> map = new HashMap<>();

    public static SoundPool createSoundPool(Context context) {
        // return new SoundPool.Builder().setMaxStreams(1).setAudioAttributes(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();
        map.clear();
        setAlarmVolume(context);
        return new SoundPool(10, 3, 0);
    }

    public static void setAlarmVolume(Context context){
        AudioManager audioManager = null;
        try {
            audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            //得到手机音乐音量的最大值
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            //得到当前手机的音量

            int mCurVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            //设置音量大小
            if (mCurVolume == 0) {
                 audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载音效
     *
     * @param context
     * @param pool
     * @param resIds
     * @return id map to manager ids.Ti can use the resId to find the sound id.
     */
    public static Map<Integer, Integer> loadSounds(Context context, SoundPool pool, int[] resIds) {
        if (resIds == null) {
            throw new NullPointerException(" load sounds error!");
        }

        pool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                Log.e("SoundPoolManager", "setOnLoadCompleteListener-- ： " + sampleId + " status " + status);
            }
        });
        map = new HashMap<Integer, Integer>();
        for (int i = 0; i < resIds.length; i++) {
            int id = pool.load(context, resIds[i], 5);
            map.put(resIds[i], id);
        }
        return map;
    }

    /**
     * play sound
     *
     * @param pool
     * @param resId
     * @return play id
     */
    public static int play(SoundPool pool, int resId) {
        int soundId = map.get(resId);
        return pool.play(soundId, 1.0f, 1.0f, 0, 0, 1);
    }

}
